<template>
	<base-layout simple>
		<article class="base-layout__inner column">
			<!-- 查询条件 -->
			<t-form
				ref="form"
				:data="queryParams"
				label-width="80px"
				layout="inline"
				class="search-form"
				colon
				label-align="right"
			>
				<t-row style="width: 100%">
					<t-col :span="3">
						<t-form-item label="用户名">
							<t-input
								v-model="queryParams.username"
								placeholder="请输入用户名"
								clearable
								style="width: 158px"
							/>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item label="邮箱">
							<t-input
								v-model="queryParams.email"
								placeholder="请输入邮箱"
								clearable
								style="width: 158px"
							/>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item label="手机">
							<t-input
								v-model="queryParams.phone"
								placeholder="请输入手机号"
								clearable
								style="width: 158px"
							/>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item label="部门">
							<t-tree-select
								v-model="queryParams.deptId"
								:data="deptTreeData"
								:keys="treeKeys"
								placeholder="请选择部门"
								clearable
								filterable
								style="width: 158px"
								:loading="deptLoading"
							/>
						</t-form-item>
					</t-col>
				</t-row>

				<t-row style="width: 100%">
					<t-col :span="3">
						<t-form-item label="状态">
							<t-select
								v-model="queryParams.status"
								placeholder="请选择状态"
								clearable
								style="width: 158px"
							>
								<t-option :value="1" label="启用" />
								<t-option :value="0" label="禁用" />
							</t-select>
						</t-form-item>
					</t-col>

					<t-col :span="3">
						<t-form-item>
							<t-space>
								<t-button theme="primary" @click="handleSearch">查询</t-button>
								<t-button theme="default" @click="handleReset">重置</t-button>
							</t-space>
						</t-form-item>
					</t-col>
				</t-row>

				<t-row style="width: 100%">
					<t-col :span="3">
						<t-row>
							<t-space>
								<t-button theme="primary" @click="handleAdd">新增账号</t-button>
							</t-space>
						</t-row>
					</t-col>
					<t-col :span="9"></t-col>
				</t-row>
			</t-form>

			<!-- 数据表格 -->
			<t-table
				ref="table"
				:data="accountData"
				:columns="columns"
				:loading="loading"
				:pagination="pagination"
				@page-change="handlePageChange"
				@page-size-change="handlePageSizeChange"
				row-key="id"
				bordered
				size="small"
			/>
		</article>

		<!-- 账号编辑抽屉 -->
		<account-form-drawer
			:visible.sync="editorVisible"
			:is-edit="isEdit"
			:current-edit-data="currentEditData"
			:dept-tree-data="deptTreeData"
			@save="handleSave"
			@close="handleCloseEditor"
			ref="accountFormDrawer"
		/>
	</base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import AccountFormDrawer from './AccountFormDrawer.vue';
import {
	Button as TButton,
	Tag as TTag,
	Table as TTable,
	TreeSelect as TTreeSelect,
	Popconfirm as TPopconfirm
} from 'tdesign-vue';
import { getAllDepts } from '@/api/dept';
import { getUserListByTenant } from '@/api/user';

export default {
	name: 'SystemAccount',
	components: {
		BaseLayout,
		AccountFormDrawer,
		TTable,
		TButton,
		TTreeSelect
	},
	data() {
		return {
			loading: false,
			editLoading: false,
			editorVisible: false,
			currentEditData: null,
			isEdit: false,
			deptLoading: false,

			// 查询参数
			queryParams: {
				username: '',
				email: '',
				phone: '',
				deptId: '',
				status: '',
			},

			// 分页参数
			pagination: {
				current: 1,
				pageSize: 10,
				total: 0,
				showJumper: true,
				showSizer: true,
			},

			// 部门树数据
			deptTreeData: [],

			// 树配置
			treeKeys: {
				value: 'id',
				label: 'name',
				children: 'children'
			},

			// 表格列配置
			columns: [
				{
					colKey: 'username',
					title: '用户名',
					width: 120,
					ellipsis: true,
					cell: (h, { row }) => {
						return row.admin?.username || '-';
					},
				},
				{
					colKey: 'deptName',
					title: '所在部门',
					width: 150,
					ellipsis: true,
					cell: (h, { row }) => {
						return row.dept?.name || '未分配';
					},
				},
				{
					colKey: 'roleNames',
					title: '所属角色',
					width: 150,
					ellipsis: true,
					cell: (h, { row }) => {
						if (row.roles && row.roles.length > 0) {
							return row.roles.map(role => role.name).join('、');
						}
						return '-';
					},
				},
				{
					colKey: 'email',
					title: '邮箱',
					width: 180,
					ellipsis: true,
				},
				{
					colKey: 'phone',
					title: '手机',
					width: 130,
					ellipsis: true,
				},
				{
					colKey: 'remark',
					title: '备注',
					width: 150,
					ellipsis: true,
					cell: (h, { row }) => {
						return row.remark || '-';
					},
				},
				{
					colKey: 'status',
					title: '状态',
					width: 100,
					align: 'center',
					cell: (h, { row }) => {
						return h(
							TTag,
							{
								props: {
									theme: row.status === 1 ? 'success' : 'danger',
									size: 'small',
									variant: 'light',
								},
							},
							row.status === 1 ? '启用' : '禁用'
						);
					},
				},
				{
					colKey: 'createdAt',
					title: '创建时间',
					width: 160,
					ellipsis: true,
					cell: (h, { row }) => {
						return row.createdAt ? new Date(row.createdAt).toLocaleString() : '-';
					},
				},
				{
					colKey: 'operate',
					title: '操作',
					width: 200,
					fixed: 'right',
					cell: (h, { row }) => {
						return h('div', { class: 'table-operations' }, [
							h(
								'TButton',
								{
									props: {
										variant: 'text',
										theme: 'primary',
										size: 'small',
									},
									on: {
										click: () => this.handleEdit(row),
									},
								},
								'编辑'
							),
							h(
								'TButton',
								{
									props: {
										variant: 'text',
										theme: 'warning',
										size: 'small',
									},
									on: {
										click: () => this.handleResetPassword(row),
									},
								},
								'重置密码'
							),
							h(
								TPopconfirm,
								{
									props: {
										content: '确认删除该账号吗？删除后不可恢复！',
									},
									on: {
										confirm: () => this.handleDelete(row),
									},
								},
								[
									h(
										'TButton',
										{
											props: {
												variant: 'text',
												theme: 'danger',
												size: 'small',
											},
										},
										'删除'
									),
								]
							),
						]);
					},
				},
			],

			// 账号数据
			accountData: [],
		};
	},

	mounted() {
		this.getDeptTreeData();
		this.getAccountList();
	},

	methods: {
		// 获取部门树数据
		async getDeptTreeData() {
			this.deptLoading = true;
			try {
				const response = await getAllDepts();
				if (response?.data?.code === 200) {
					this.deptTreeData = response.data.data || [];
				} else {
					this.$message.error('获取部门数据失败');
				}
			} catch (error) {
				console.error('获取部门数据失败:', error);
				this.$message.error('获取部门数据失败');
			} finally {
				this.deptLoading = false;
			}
		},

		// 获取账号列表
		async getAccountList() {
			this.loading = true;
			try {
				// 构建查询参数，过滤掉空值
				const queryData = {};
				if (this.queryParams.username && this.queryParams.username.trim()) {
					queryData.username = this.queryParams.username.trim();
				}
				if (this.queryParams.email && this.queryParams.email.trim()) {
					queryData.email = this.queryParams.email.trim();
				}
				if (this.queryParams.phone && this.queryParams.phone.trim()) {
					queryData.phone = this.queryParams.phone.trim();
				}
				if (this.queryParams.deptId !== '' && this.queryParams.deptId !== null && this.queryParams.deptId !== undefined) {
					queryData.deptId = this.queryParams.deptId;
				}
				if (this.queryParams.status !== '' && this.queryParams.status !== null && this.queryParams.status !== undefined) {
					queryData.status = this.queryParams.status;
				}

				const params = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
					...queryData
				};

				const response = await getUserListByTenant(params);
				console.log('账号列表响应:', response);

				if (response?.data?.code === 200) {
					this.accountData = response?.data?.data?.items || [];
					this.pagination.total = response?.data?.data?.meta?.totalItems || 0;
				} else {
					throw new Error(response?.data?.message ?? '获取账号列表失败');
				}
			} catch (error) {
				console.error('获取账号列表失败:', error);
				this.$message.error('获取账号列表失败');
				// 使用模拟数据
				this.accountData = this.getMockAccountData();
				this.pagination.total = this.accountData.length;
			} finally {
				this.loading = false;
			}
		},

		// 模拟账号数据
		getMockAccountData() {
			return [
				{
					id: 1,
					username: 'admin',
					nickname: '超级管理员',
					realName: '管理员',
					email: 'admin@example.com',
					phone: '13800138001',
					deptName: '技术部',
					roleNames: ['超级管理员'],
					remark: '系统管理员账号',
					status: 1,
					createdAt: '2024-01-01 10:00:00'
				},
				{
					id: 2,
					username: 'user001',
					nickname: '张小三',
					realName: '张三',
					email: 'zhangsan@example.com',
					phone: '13800138002',
					deptName: '市场部',
					roleNames: ['普通用户', '市场专员'],
					remark: '市场部员工',
					status: 1,
					createdAt: '2024-01-02 09:00:00'
				},
				{
					id: 3,
					username: 'user002',
					nickname: '李四哥',
					realName: '李四',
					email: 'lisi@example.com',
					phone: '13800138003',
					deptName: '人事部',
					roleNames: ['普通用户'],
					remark: '人事部新员工',
					status: 0,
					createdAt: '2024-01-03 11:00:00'
				},
				{
					id: 4,
					username: 'developer',
					nickname: '开发小能手',
					realName: '王五',
					email: 'wangwu@example.com',
					phone: '13800138004',
					deptName: '技术部',
					roleNames: ['开发者', '技术主管'],
					remark: '资深开发工程师',
					status: 1,
					createdAt: '2024-01-04 14:30:00'
				}
			];
		},

		// 查询
		handleSearch() {
			this.pagination.current = 1;
			this.getAccountList();
		},

		// 重置查询条件
		handleReset() {
			this.queryParams = {
				username: '',
				email: '',
				phone: '',
				deptId: '',
				status: '',
			};
			this.pagination.current = 1;
			this.getAccountList();
		},

		// 分页改变
		handlePageChange(pageInfo) {
			this.pagination.current = pageInfo.current;
			this.getAccountList();
		},

		// 分页大小改变
		handlePageSizeChange(pageInfo) {
			this.pagination.pageSize = pageInfo.pageSize;
			this.pagination.current = 1;
			this.getAccountList();
		},

		// 新增账号
		handleAdd() {
			this.isEdit = false;
			this.currentEditData = null;
			this.editorVisible = true;
		},

		// 编辑账号
		async handleEdit(row) {
			if (this.editLoading) return;

			try {
				this.editLoading = true;
				this.isEdit = true;
				this.currentEditData = { ...row };
				this.editorVisible = true;
			} catch (error) {
				console.error('编辑账号失败:', error);
				this.$message.error('编辑账号失败');
			} finally {
				this.editLoading = false;
			}
		},

		// 重置密码
		async handleResetPassword(row) {
			try {
				// 这里应该调用重置密码的API
				this.$message.success(`已重置用户 ${row.username} 的密码`);
			} catch (error) {
				console.error('重置密码失败:', error);
				this.$message.error('重置密码失败');
			}
		},

		// 删除账号
		async handleDelete(row) {
			try {
				// 这里应该调用删除账号的API
				this.$message.success(`已删除用户 ${row.username}`);
				this.getAccountList();
			} catch (error) {
				console.error('删除账号失败:', error);
				this.$message.error('删除账号失败');
			}
		},

		// 保存账号
		async handleSave(formData) {
			try {
				// 设置抽屉的保存loading状态
				this.$refs.accountFormDrawer.setSaveLoading(true);

				// 这里应该调用保存账号的API
				if (this.isEdit) {
					this.$message.success('账号更新成功');
				} else {
					this.$message.success('账号创建成功');
				}

				this.editorVisible = false;
				this.getAccountList();
			} catch (error) {
				console.error('保存账号失败:', error);
				this.$message.error('保存账号失败');
			} finally {
				this.$refs.accountFormDrawer.setSaveLoading(false);
			}
		},

		// 关闭编辑器
		handleCloseEditor() {
			this.editorVisible = false;
			this.currentEditData = null;
		},
	},
};
</script>

<style lang="less" scoped>
.search-form {
	background: #fff;
}

/deep/ .t-form-item {
	margin-bottom: 0;
}

// 确保label右对齐
/deep/ .t-form__label {
	text-align: right !important;
	justify-content: flex-end !important;
	padding-right: var(--td-comp-paddingLR-s);
}

/deep/ .t-form-item__label {
	text-align: right !important;
	justify-content: flex-end !important;
}

/deep/ .table-operations {
	.t-button {
		margin-right: 8px;
	}
}

/deep/ .t-table {
	.t-table__header {
		background-color: #f5f7fa;
	}
}
</style>